package me.jiatao.taobaotools.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by JiaTao on 2018/7/18.
 * Email: 535318720@qq.com
 * Version: 1.0
 * Description:
 */
public class BaseActivity extends AppCompatActivity {
    protected Context context;
    protected BaseActivity activity;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        activity = this;
    }

    public void setWebViewHtml(String strHtml){

    }



    //region  权限管理

    public interface UOPermissionCallback {
        void hasPermission();

        void noPermission();
    }


    private int permissionRequestCode = 88;
    private UOPermissionCallback permissionRunnable;

    /**
     * Android M运行时权限请求封装
     *
     * @param permissionDes 权限描述
     * @param runnable      请求权限回调
     * @param permissions   请求的权限（数组类型），直接从Manifest中读取相应的值，比如Manifest.permission.WRITE_CONTACTS
     */
    public void performCodeWithPermission(String permissionDes, UOPermissionCallback runnable, String... permissions) {
        if (permissions == null || permissions.length == 0) return;

        this.permissionRunnable = runnable;

        int targetSdk = getApplicationInfo().targetSdkVersion;

        if ((targetSdk < 23) || //如果当前apk的版本 小于 23 不需要授权
                (Build.VERSION.SDK_INT < 23) || //如果当前的系统版本 小于 23 不需要授权
                checkPermissionGranted(permissions) //如果当前的权限已经授权
                ) {
            if (permissionRunnable != null) {
                permissionRunnable.hasPermission();
                permissionRunnable = null;
            }
        } else {
            //permission has not been granted.
            requestPermission(permissionDes, permissionRequestCode, permissions);
        }

    }

    /**
     * 检测当前权限是否已经授权
     *
     * @param permissions
     * @return
     */
    @SuppressLint("NewApi")
    private boolean checkPermissionGranted(String[] permissions) {
        boolean flag = true;
//        for (String p : permissions) {
//            if (ActivityCompat.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED) {
//                flag = false;
//                break;
//            }
//        }

        int targetSdkVersion = 0;
        try {
            final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            targetSdkVersion = info.applicationInfo.targetSdkVersion;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        if (targetSdkVersion >= 23) {
            // targetSdkVersion >= Android M, we can
            // use Context#checkSelfPermission
            for (String pem : permissions) {
                if (ContextCompat.checkSelfPermission(context,pem) != PackageManager.PERMISSION_GRANTED) {
                    flag = false;
                    break;
                }
            }
        } else {
            // targetSdkVersion < Android M, we have to use PermissionChecker
            for (String pem : permissions) {
                if (PermissionChecker.checkSelfPermission(context, pem) != PermissionChecker.PERMISSION_GRANTED) {
                    flag = false;
                    break;
                }
            }
        }


        return flag;
    }


    /**
     * 申请权限
     *
     * @param permissionDes
     * @param requestCode
     * @param permissions
     */
    private void requestPermission(String permissionDes, final int requestCode, final String[] permissions) {
        if (shouldShowRequestPermissionRationale(permissions)) {

            //如果用户之前拒绝过此权限，再提示一次准备授权相关权限
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage(permissionDes)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(activity, permissions, requestCode);
                        }
                    }).show();

        } else {
            // Contact permissions have not been granted yet. Request them directly.
            ActivityCompat.requestPermissions(activity, permissions, requestCode);
        }
    }

    private boolean shouldShowRequestPermissionRationale(String[] permissions) {
        boolean flag = false;
        for (String p : permissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, p)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == permissionRequestCode) {
            if (verifyPermissions(grantResults)) {
                //已经申请权限
                if (permissionRunnable != null) {
                    permissionRunnable.hasPermission();
                    permissionRunnable = null;
                }
            } else {
                //暂无权限执行相关操作
                if (permissionRunnable != null) {
                    permissionRunnable.noPermission();
                    permissionRunnable = null;
                }
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }

    public boolean verifyPermissions(int[] grantResults) {
        // At least one result must be checked.
        if (grantResults.length < 1) {
            return false;
        }

        // Verify that each required permission has been granted, otherwise return false.
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    //endregion
}
